package com.osce.common.utils;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.doudou.core.lang.Option;
import com.doudou.core.io.IoUtil;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author zzxjs
 * @since 2023/11/9
 */
public class SocketUtil {

    /**
     * 发送消息
     */
    public static void sendMessage(WebSocketSession session, String message) {
        Option.of(session).ifNotNull(s -> {
            try {
                s.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }


    public static JSONObject getQuerys(WebSocketSession session) {
        return JSONUtil.parseObj(UrlBuilder.of(session.getUri(), Charset.defaultCharset()).getQuery().getQueryMap());
    }

    /**
     * 释放资源
     */
    public static void close(WebSocketSession session) {
        IoUtil.close(session);
    }

}
